﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

[Serializable]
public class AlbumManager
{
    private AlbumStorage _albumStorage;

    private Album TurnDataRowIntoAlbum(DataRow row)
    {
        return new Album(int.Parse(row[0].ToString()), row[1].ToString(), row[2].ToString(), 
            row[3].ToString(), DateTime.Parse(row[4].ToString()));
    }
    public AlbumManager()
    {
        _albumStorage = new AlbumStorage();
    }

    public int CreateAlbum(Album album)
    {
        return _albumStorage.CreateAlbum(album.AlbumName, album.Author, album.FolderPath, album.CreationDate);
    }

    public Album[] GetAllAlbums()
    {
        return (from drAlbumRow in _albumStorage.GetAllAlbumsTable().Rows.OfType<DataRow>()
                //select new Album(int.Parse(drAlbumRow[0].ToString()), drAlbumRow[1].ToString(), drAlbumRow[2].ToString(), drAlbumRow[3].ToString(), DateTime.Parse(drAlbumRow[4].ToString())))
                select TurnDataRowIntoAlbum(drAlbumRow))
                .ToArray();
    }

    public Album GetAlbumById(int id)
    {
        //Album album;
        DataRow drAlbumRow = _albumStorage.GetAlbumRowById(id);
        //album = new Album(int.Parse(drAlbumRow[0].ToString()), drAlbumRow[1].ToString(), drAlbumRow[2].ToString(), drAlbumRow[3].ToString(), DateTime.Parse(drAlbumRow[4].ToString()));
        return TurnDataRowIntoAlbum(drAlbumRow);
    }

    public bool UpdateAlbum(Album album)
    {
        return _albumStorage.UpdateAlbum(album.ID, album.AlbumName, album.FolderPath);
    }

    public bool DeleteAlbum(int id)
    {
        return _albumStorage.DeleteAlbum(id);
    }

    public string RenameAlbum(Album album, string newName)
    {
        if (string.IsNullOrEmpty(newName))
        {
            return "EmptyField";
        }

        UserDataHandler user = new UserDataHandler();
        if (user.CheckAccessRights(album) == false)
        {
            return "NoRights";
        }

        album.AlbumName = newName;
        bool check = UpdateAlbum(album);
        return check ? "Success" : "Error";
    }
}